$(document).ready(function() {
	$(".group-number").hide();
	changeSelection();
});

$(document).delegate('#group', 'change', function() {
	if ($(this).val()==-2) {
		$(".group-number").show();
	} else {
		$(".group-number").hide();
	}
});

$(document).delegate('#session-count', 'change', function() {
	changeSelection();
});

function changeSelection() {
	num = $("#session-count").val();
	for (i = 1; i <= parseInt(num); i++) {
		$("#session-" + i).show();
	}
	for (i = parseInt(num) + 1; i <= 4; i++) {
		$("#session-" + i).hide();
	}
}

function addCourse() {
	data = $("#course-form").serialize();
	numOfSessions = $("#session-count").val();
	if ($("#group").val() == "-1") {
		$("#course-error").html("You must select a group");
		return;
	}
	for (i = 1; i <= parseInt(numOfSessions); i++) {
		day = parseInt($("#day-" + i).val());
		startHour = parseInt($("#start-" + i).val());
		endHour = parseInt($("#end-" + i).val());
		if ((day == -1) || (startHour == -1) || (endHour == -1)) {
			$("#course-error").html(
					"Choose a day and time for all your sessions");
			return;
		}
		start = (day * 10 + startHour);
		end = (day * 10 + endHour);
		if (start >= end) {
			$("#course-error")
					.html(
							"Sessions hours are incorrect (start hour must be smaller than end hour)");
			return;
		} else if (end - start > 4) {
			$("#course-error")
					.html(
							"Sessions hours are incorrect (Each session can be upto 4 hours)");
			return;
		}
		data += "&start-" + i + "=" + start + "&end-" + i + "=" + end;
	}
	data += "&numOfSlots=" + numOfSessions;
	$.ajax({
		type : "POST",
		url : $("#project-base").val()+'Courses',
		async : false,
		data : data,
		success : function(msg) {
			$("#course-error").html("");
			window.location.href = $("#project-base").val()+"Courses/" + msg;
		},
		error : function(msg) {
			$("#course-error").html(msg.responseText);
		}
	});
}
